package EX04_11.txt;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import java.io.File;
public class EX04_11 extends Activity {
private Button mButton;
private TextView mTextView;
private EditText mEditText;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button)findViewById(R.id.myButton);
mEditText = (EditText)findViewById(R.id.myEditText);
mTextView = (TextView)findViewById(R.id.myTextView);
mButton.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchFile();
}
});
}
private void searchFile()
{
String keyWord = mEditText.getText().toString();
String resoult = "";
if (keyWord.equals("")) {
mTextView.setText("搜索文件不能为空!");
} else {
File[] files = new File("/").listFiles();
for(File file:files)
{
if (file.getName().indexOf(keyWord)>0) {
resoult += file.getPath() + "\n";
}
}
}
if (resoult.equals("")) {
mTextView.setText("搜索不到任何文件。");
} else {
mTextView.setText(resoult);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id = "@+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id = "@+id/myButton"
android:layout_gravity = "center"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text = "搜索"
/>
<TextView
android:id = "@+id/myTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>