【问题标题】:How do I start another activity when a button defined in main.xml is clicked单击 main.xml 中定义的按钮时如何启动另一个活动
【发布时间】:2012-04-04 07:59:15
【问题描述】:

我有两节课。一个是Main,另一个是HelloWorld。当我单击 main.xml 中定义的按钮时,我希望它显示 HelloWorld 类中定义的消息以启动。当我单击按钮时,它不执行任何操作。代码如下。如果还有什么需要提出的,请告诉我。谢谢

Main.java

public class Main extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
long start;
long stop;
int x, y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat ;
int longi; 





@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button orderButton = (Button)findViewById(R.id.button1);

    orderButton.setOnClickListener(new View.OnClickListener() {

      public void onClick(View view) {
        Intent intent = new Intent(Main.this, HelloWorld.class);
        startActivity(intent);
      };
    });

    map = (MapView)findViewById(R.id.mv);
    map.setBuiltInZoomControls(true);

    Touchy t = new Touchy();
    overlayList = map.getOverlays();
    overlayList.add(t);



    d = getResources().getDrawable(R.drawable.pinn);



    //Placing pintpoint
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();

    towers = lm.getBestProvider(crit, false);
    Location location = lm.getLastKnownLocation(towers);

    if (location != null){
        lat = (int) (location.getLatitude() *1E6);
        longi= (int) (location.getLongitude() *1E6);



        GeoPoint ourLocation = new GeoPoint(lat,longi);
        OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
        CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
        custom.insertPinpoint(overlayItem);
        overlayList.add(custom);
    }else{
       Toast.makeText(Main.this, "Couldnt get provider", Toast.LENGTH_SHORT).show();
    }





}

@Override
protected void onPause() {
    // TODO Auto-generated method stub

    super.onPause();
    lm.removeUpdates(this);
}


     @Override
protected void onResume() {
    // TODO Auto-generated method stub

    super.onResume();
    lm.requestLocationUpdates(towers, 500, 1, this );
}


    @Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}



class Touchy extends Overlay{
    public boolean onTouchEvent(MotionEvent e, MapView m){
    if (e.getAction() == MotionEvent.ACTION_DOWN){
        start = e.getEventTime();

    }
    if (e.getAction() == MotionEvent.ACTION_UP){
        stop = e.getEventTime();
        x = (int) e.getX();
        y = (int) e.getY();
        touchedPoint = map.getProjection().fromPixels(x, y);

    }
    if (stop - start > 1500){
        AlertDialog alert = new AlertDialog.Builder(Main.this).create();
        alert.setTitle("Pick Option");


        alert.setButton("Hello", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

    OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
        CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
                custom.insertPinpoint(overlayItem);
                overlayList.add(custom);



        }
        });
    alert.setButton3("Get Address", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
    Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
    try{
    List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() /      1E6, touchedPoint.getLongitudeE6() / 1E6 , 1);
                if (address.size() > 0){
                    String display = "";
        for (int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){

                display += address.get(0).getAddressLine(i) + "\n";
                    }
    Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                    t.show();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
            }
        }});
    alert.setButton2("Toggle View", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                if (map.isSatellite()){
                    map.setSatellite(false);
                    map.setStreetView(true);
                }else{
                    map.setStreetView(false);
                    map.setSatellite(true);
                }
            }
});


    alert.setButton("Place a Pin", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

    OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
           CustomPinPoint custom = new CustomPinPoint(d,Main.this); 
                custom.insertPinpoint(overlayItem);
                overlayList.add(custom);

            }


        });
        alert.show();
        return true;
    }

        return false;
    }

}



public void onLocationChanged(Location l) {
    // TODO Auto-generated method stub
    lat = (int) (l.getLatitude() *1E6);
    longi = (int) (l.getLongitude() *1E6);
    GeoPoint ourLocation = new GeoPoint(lat,longi);
    OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
    CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
    custom.insertPinpoint(overlayItem);
    overlayList.add(custom);

}




public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}




public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}




public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

    }

HelloWorld.java

import com.google.android.maps.OverlayItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class HelloWorld extends Activity
{

        protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v)
            {
                Toast.makeText(HelloWorld.this, "you clicked on button![enter image description here][3]", Toast.LENGTH_LONG).show();
            }
});

} }

我也写过

  <activity android:name=".HelloWorld" /> 

在我的清单中

【问题讨论】:

    标签: android button android-activity android-intent


    【解决方案1】:

    您的第二个活动HelloWorld 没有设置内容视图,因此它找不到Button,您抛出了NullPointerException。您必须设置一个带有setContentView 的contentView,其中包含ID 为R.id.button1Button,就像您在MainActivity 中所做的那样。

    您的HelloWorld 活动:

    public class HelloWorld<AlertDialogActivity> extends Activity{
    
                 protected void onCreate(Bundle icicle) {
                 super.onCreate(icicle);
                 setContentView(R.layout.layout_hello);
    
                 final Button button = (Button) findViewById(R.id.button1);
                 button.setOnClickListener(new View.OnClickListener() {
                     public void onClick(View view) {
          Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
                     }
                 });
        }
    }
    

    其中R.layout.layout_hello代表res/layout文件夹中的一个xml文件(命名为layout_hello.xml):

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
    
            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button1" />
    </LinearLayout>
    

    这与您在MainActivity 中所做的相同。

    【讨论】:

    • 我在 main.xml 中创建了一个按钮,所以当我单击该按钮时,HelloWorld 活动应该可以工作。我该怎么做呢。很抱歉打扰您。
    • 兄弟,我想你没有明白我想说的话。请参阅我在 main.xml 中创建了一个按钮,因此当我单击此按钮时,我的 HelloWorld 活动应该开始。因为我试过你说的。不工作。
    • @MehulRastogi 如果您在第二个活动HelloWorld 中没有内容视图,那么应用程序将Force Close。此外,您的第二个类的名称应该是HelloWorld,没有通用参数&lt;AlertDialogActivity&gt;,就像这个public class HelloWorld extends Activity 。如果这不起作用,请在Logcat 中发布您遇到的异常。
    • 04-04 17:10:34.583: E/MapActivity(312): 无法获取连接工厂客户端
    • @MehulRastogi 这似乎是与MapActivity 相关的错误。我不知道是什么原因造成的,但有一些关于这个问题的问题,在快速搜索中我找到了stackoverflow.com/questions/5848544/…stackoverflow.com/questions/2199403/…,但还有更多。
    【解决方案2】:

    简单的方法

    main.xml 中包含android:onClick="onClickMyButton" 作为Button 的属性

    从这个Button中删除onClickListener

    现在在您的 Main Activity 中定义此方法

    public void onClickMyButton(View view){
    
    Intent intent = new Intent(Main.this, HelloWorld.class);
            startActivity(intent);
    
    
    }
    

    现在启动您的应用程序,它应该可以正常工作了

    【讨论】:

      【解决方案3】:

      你为什么评论那句话? //setContentView(R.layout.content_layout_id);

      活动正在寻找按钮R.id.button1 是一个空视图。

      【讨论】:

        【解决方案4】:

        你必须使用 setContentView()

        取消注释该代码并重试

        【讨论】:

          猜你喜欢
          • 2012-02-12
          • 1970-01-01
          • 2015-03-12
          • 1970-01-01
          • 1970-01-01
          • 2013-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多