使用setContentView加载布局时,应用程序停止工作

时间:2014-03-25 10:03:48

标签: java android android-layout classcastexception

这是XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search_lyt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:name="search_act"
tools:context="com.example.app.Hisp$PlaceholderFragment">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:src="@drawable/hispania_lgs"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back"
    android:id="@+id/back2"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Info"
    android:id="@+id/info2"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/model_list"
    android:layout_below="@+id/textViewML"
    android:layout_alignParentRight="true"
    android:layout_above="@+id/back2"
    android:choiceMode="singleChoice" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Select any of the models below and press Info for the model's specifications"
    android:id="@+id/textViewML"
    android:layout_below="@+id/imageView2"
    android:layout_alignLeft="@+id/model_list" />

使用setContentView方法会导致'Application stopped working'。

setContentView(R.layout.search_hisp);

有关如何解决此问题的任何想法?我对Android开发还很陌生,仍然试图找到如何以正确的方式切换布局。

好吧,即使我将onCreate()'setContentView更改为R.layout.search_hisp并在启动时给我错误。所以我的猜测可能来自XML文件或其他东西。

提前致谢!

编辑,出现错误:

&GT;

 03-25 12:10:23.415  20858-20858/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
            at com.example.app.Hisp.beginSearch(Hisp.java:121)
            at com.example.app.Hisp$3.onClick(Hisp.java:107)
            at android.view.View.performClick(View.java:4231)
            at android.view.View$PerformClick.run(View.java:17537)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:158)
            at android.app.ActivityThread.main(ActivityThread.java:5751)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
            at dalvik.system.NativeStart.main(Native Method)
03-25 12:10:23.420      515-550/? E/EmbeddedLogger﹕ App crashed! Process: com.example.app
03-25 12:10:23.420      515-550/? E/EmbeddedLogger﹕ App crashed! Package: com.example.app v1 (1.0)
03-25 12:10:23.420      515-550/? E/EmbeddedLogger﹕ Application Label: Hisp_Selector

这是代码:

package com.example.app;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.preference.DialogPreference;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.ViewGroup;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.widget.LinearLayout;

public class Hisp extends ActionBarActivity {

    public static ActionBarActivity activity;

    Context ctx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        activity = this;

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_hisp);

        TextView txt = (TextView) findViewById(R.id.textViewML);

        Button btn = (Button) g(R.id.search);
        Button rst = (Button) g(R.id.reset);

        rst.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(getIntent());
            }
        });

        OnClickListener _rdb = new OnClickListener() {
            @Override
            public void onClick(View view) {
                ((CheckBox) g(R.id.R134a)).setChecked(false);
                ((CheckBox) g(R.id.R22)).setChecked(false);
                ((CheckBox) g(R.id.R404A)).setChecked(false);
                ((CheckBox) g(R.id.R507A)).setChecked(false);

                ((CheckBox) view).setChecked(true);
            }
        };

        ((CheckBox) g(R.id.R134a)).setOnClickListener(_rdb);
        ((CheckBox) g(R.id.R22)).setOnClickListener(_rdb);
        ((CheckBox) g(R.id.R404A)).setOnClickListener(_rdb);
        ((CheckBox) g(R.id.R507A)).setOnClickListener(_rdb);

        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                beginSearch();
            }
        });
        /*
        if (stanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
        */
    }

    public void beginSearch() {

        ((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());

        Boolean err = false;

        try {

            if (!(Double.parseDouble((((EditText) g(R.id.capacity)).getText().toString().trim())) >= 0 &&
                isBetween(-35, 5, Integer.parseInt(((EditText) g(R.id.evaptemp)).getText().toString().trim()))  &&
                isBetween(28, 58, Integer.parseInt(((EditText) g(R.id.condtemp)).getText().toString().trim())) &&
                isBetween(5, 13, Integer.parseInt(((EditText) g(R.id.dt1)).getText().toString().trim()))
            )) err = true;

        } catch(Exception e) {
            err = true;
        }

        if (err) {
            showMessageBox("ERROR", "Make sure you have filled all the fields correctly.", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
        } else {
            setContentView(R.layout.search_hisp);
        }
    }

    public View g(int id) {
        return activity.findViewById(id);
    }

    public Boolean isBetween(Integer i1, Integer i2, Integer ix) {
        if (ix >= i1 && ix <= i2) return true;

        return false;
    }

    public void showMessageBox(Object ttl, Object msg, DialogInterface.OnClickListener rt) {
        new AlertDialog.Builder(activity)
                .setMessage(msg.toString())
                .setTitle(ttl.toString())
                .setCancelable(false)
                .setNeutralButton(android.R.string.ok, rt)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.hisp, 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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */

    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_hisp, container, false);
            return rootView;
        }
    }

}

5 个答案:

答案 0 :(得分:1)

加入onCreate:

TextView textViewML = (TextView) findViewById(R.id.textViewML);

答案 1 :(得分:1)

因为在onCreate()中你使用了

 EditText textViewML = (EditText) findViewById(R.id.textViewML);

而不是

 TextView txt = (TextView) findViewById(R.id.textViewML);

所以你遇到了问题。所以你需要在setContentView()方法之后使用。

 TextView txt = (TextView) findViewById(R.id.textViewML);

答案 2 :(得分:0)

您正在将Textview转换为EditText而不执行该操作

EditText textViewML = (EditText) findViewById(R.id.textViewML);

将其更改为

TextView textViewML = (TextView) findViewById(R.id.textViewML);

答案 3 :(得分:0)

异常不是你的java文件中的布局文件,而是将TextView转换为EditText。

您无法将超类投射到子类中。 你可以将Sub类转换为Super Class。

您可以将EditText转换为TextView,但不能将TextView转换为EditText。

更改此行

TextView txt = (TextView) findViewById(R.id.textViewML);

感谢名单

答案 4 :(得分:0)

错误来自

((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());

非常感谢你们指出这一点!