activity_main.xml代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
<TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is TextView" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button"/> <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/button" android:layout_marginTop="14dp" android:ems="10" android:hint="Type something here" > <requestFocus /> </EditText>
MainActivity.java代码:
package com.example.class3;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button button;
private EditText editText;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
editText=(EditText) findViewById(R.id.edit_text);
button.setOnClickListener((OnClickListener) this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.button:
String inputText=editText.getText().toString();
Toast.makeText(MainActivity.this,inputText,
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
感觉自己排版都好乱- -
Button button = (Button) findViewById(R.id.button); //这个button有两个同名的定义
button.setOnClickListener((OnClickListener) this); //button.setOnClickListener(this); 这样就行了
前面已经写了:private Button button;所以不用写Button button = (Button) findViewById(R.id.button);直接实例化就可以了,button设置监听事件直接用this就可以了,也可以使用匿名内部类进行添加。
你先把logcat的红字贴出来我们才好分析嘛