добавление вида в макет, отличный от макета, отображаемого на экране - PullRequest
0 голосов
/ 16 декабря 2010

У меня есть основной макет с кнопкой, при касании кнопки он переключит макет с помощью setcontentView и добавит кнопку во вновь просмотренный макет. Я получаю ошибку во время выполнения.

мой код:

package com.android.ui;

import android.app.Activity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;

public class mainprog extends Activity implements OnTouchListener {
    /** Called when the activity is first created. */
    private final static int START_DRAGGING = 0;
    private final static int STOP_DRAGGING = 1;
    public Button btn1;
    public Button btn;
    public FrameLayout layout;
    private int status;
    public LayoutParams params;
    public FrameLayout layout1;
    public ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        layout = (FrameLayout) findViewById(R.id.LinearLayout01);
        // layout.setOnTouchListener(this);
        layout1 = (FrameLayout) findViewById(R.id.LinearLayout02);
        btn1 = (Button) findViewById(R.id.btn1);
        btn = (Button) findViewById(R.id.btn);
        btn.setDrawingCacheEnabled(true);
        btn.setOnTouchListener(this);
        params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                                  LayoutParams.WRAP_CONTENT);

    }

    public boolean onTouch(View v, MotionEvent me) {

        if (me.getAction() == MotionEvent.ACTION_DOWN) {
            status = START_DRAGGING;
            image = new ImageView(this);
            image.setImageBitmap(btn.getDrawingCache());
            setContentView(R.layout.draw);
            layout1.addView(image,params);

        }

        return false;

    }

}

my main.xml

<?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="center" android:id="@+id/LinearLayout01"
android:paddingLeft="0dip">

<Button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/btn"
    android:text="Drag Me"
    ></Button>
    </FrameLayout>`

my draw.xml

<?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:gravity="center" 
android:id="@+id/LinearLayout02"
android:paddingLeft="0dip"
>

<Button 
android:layout_width="wrap_content" 
android:id="@+id/btn1"
android:layout_height="wrap_content"
android:text="Drag Meeeeeee"
 ></Button>
</FrameLayout>`

LogCat

     `I/ActivityManager(   52): Displayed activity com.android.ui/.mainprog: 1156 ms (total 1156 ms)

 D/AndroidRuntime(  260): Shutting down VM

 W/dalvikvm(  260): threadid=3: thread exiting with uncaught exception   (group=0x4001b188)

 E/AndroidRuntime(  260): Uncaught handler: thread main exiting due to uncaught exception

 E/AndroidRuntime(  260): java.lang.NullPointerException

 E/AndroidRuntime(  260):   at com.android.ui.mainprog.onTouch(mainprog.java:47)

 E/AndroidRuntime(  260):   at android.view.View.dispatchTouchEvent(View.java:3705)

 E/AndroidRuntime(  260):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:822)

 E/AndroidRuntime(  260):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:822)

   E/AndroidRuntime(  260):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:822)

   E/AndroidRuntime(  260):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:822)

    E/AndroidRuntime(  260):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)

    E/AndroidRuntime(  260):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)

    E/AndroidRuntime(  260):    at android.app.Activity.dispatchTouchEvent(Activity.java:2061)

  E/AndroidRuntime(  260):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)

  E/AndroidRuntime(  260):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)

  E/AndroidRuntime(  260):  at android.os.Handler.dispatchMessage(Handler.java:99)

  E/AndroidRuntime(  260):  at android.os.Looper.loop(Looper.java:123)

  E/AndroidRuntime(  260):  at android.app.ActivityThread.main(ActivityThread.java:4363)

  E/AndroidRuntime(  260):  at java.lang.reflect.Method.invokeNative(Native Method)

  E/AndroidRuntime(  260):  at java.lang.reflect.Method.invoke(Method.java:521)

  E/AndroidRuntime(  260):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)

   E/AndroidRuntime(  260):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

   E/AndroidRuntime(  260):     at dalvik.system.NativeStart.main(Native Method)

    I/Process (   52): Sending signal. PID: 260 SIG: 3

   I/dalvikvm(  260): threadid=7: reacting to signal 3

   I/dalvikvm(  260): Wrote stack trace to '/data/anr/traces.txt'

   I/Process (  260): Sending signal. PID: 260 SIG: 9

   I/ActivityManager(   52): Process com.android.ui (pid 260) has died.

    I/WindowManager(   52): WIN DEATH: Window{43d379c0     com.android.ui/com.android.ui.mainprog paused=false}

   I/UsageStats(   52): Unexpected resume of com.android.launcher while already resumed in com.android.ui

    E/gralloc (   52): [unregister] handle 0x4c23d0 still locked (state=40000001)

    W/InputManagerService(   52): Got RemoteException sending setActive(false) notification to pid 260 uid 10024  `

1 Ответ

0 голосов
/ 25 июня 2011

Ваш подход к решению этой проблемы - сначала неправильная ошибка

setContentView(R.layout.main);
layout = (FrameLayout) findViewById(R.id.LinearLayout01);
// layout.setOnTouchListener(this);
layout1 = (FrameLayout) mistake first

, поэтому здесь настроен ваш файл main.xml, поэтому layout1 будет нулевым.

Я посоветую вам использоватьonClickListener для кнопки, вместо ontouch

, затем внутри метода onClick с использованием инфлятора макета загрузите XML-макет к объекту просмотра, а затем с помощью этого объекта просмотра вызовите findviewById, например obj.findViewById(R.id.LinearLayout01);

, затем добавьте изображениев этом она решит вашу проблему.

...