android手机编程2.3.1
先在主activity文件旁边再新建个文件,方法是,目录上点鼠标右键然后new->activity->empty activity起文件名为SecondActivity,文件代码如下:package com.example.xinwei.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button btn =(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
再打开layout目录下的activity_second.xml文件,修改代码为:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_name"
android:id="@+id/btn"/>
</LinearLayout>
然后打开values目录下strings.xml文件修改为:
<resources>
<string name="app_name">Test</string>
<string name="m_titlename">Add</string>
<string name="m_remove">Remove</string>
<string name="button_name">Finish</string>
</resources>
然后再frist_layout.xml文件下再添加个按钮:
<Button
android:id="@+id/button_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button_3"
></Button>
把主文件MainActivity.java修改为:
package com.example.xinwei.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "you clicked button1", Toast.LENGTH_SHORT).show();
}
});
Button button3=(Button)findViewById(R.id.button_3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_item:
Toast.makeText(this, "You clicked add", Toast.LENGTH_SHORT).show();
break;
case R.id.remove_item:
Toast.makeText(this, "You clicked remove", Toast.LENGTH_SHORT).show();
break;
default:
}
return super.onOptionsItemSelected(item);
}
void myClick(View v){
Toast.makeText(this, "这是我的方法", Toast.LENGTH_SHORT).show();
}
}
打开虚拟机运行程序,点击第三个按钮就会弹出第二个活动了,效果图:
页:
[1]