如何在Fragment类中使用布局元素

时间:2018-06-25 13:12:53

标签: java android android-layout fragment

在这里,我使用Fragment在Android中创建了一个导航栏。
现在,我需要使用Fragment类及其XML文件来打印数据,但是我无法以正常方式获取ID。

Profile.java

        package com.example.dhruv.dez;

    import android.app.Activity;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;

    public class Profile extends Fragment {
        @Nullable

   //Below Line Gives Error
   BackgroundTask b = new BackgroundTask(this);

    TextView t1;

        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.profile, container, false);

        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            //Below Line Gives Error
            t1=FindViewById(R.id.username);

            getActivity().setTitle("PROFILE");


        }

    }

profile.xml

        <?xml version="1.0" encoding="utf-8"?>
    <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">


    <TextView
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:text="PROFILE"
        android:id="@+id/username"/>

    </RelativeLayout>

BackgroundTask.java

        public class BackgroundTask extends AsyncTask<String,Void,String>{

        Context ctx;

        public BackgroundTask(Context ctx)
        {
            this.ctx=ctx;
        }

        @Override
        protected String doInBackground(String... params) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            String work = params[0];

            if (work.equals("register")) {

                String name= params[1];
                String email = params[2];
                String mobno= params[3];
                String pass = params[4];
                try {
                    String login_url = "http://myweb.in/dhruv/signup.php";
                    URL url = new URL(login_url);
                    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                    huc.setRequestMethod("POST");
                    huc.setDoOutput(true);
                    OutputStream os = huc.getOutputStream();
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&"

                            + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") +"&"
                            + URLEncoder.encode("mobno", "UTF-8") + "=" + URLEncoder.encode(mobno, "UTF-8") +"&"
                            + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
                    Log.w("Error", data);
                    bw.write(data);
                    bw.flush();
                    bw.close();
                    os.close();
                    InputStream is = huc.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
                    String respone = br.readLine();
                    Log.w("Response", respone);
                    is.close();
                    return respone;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

为什么我在片段类中不能使用Background任务对象? 我可以知道为什么会出现这个问题吗?
在Android项目中使用fragmnets安全吗?
有更好的方法吗?

6 个答案:

答案 0 :(得分:0)

在一个片段中,您必须使用:

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    t1 = (TextView) view.findViewById(R.id.username);
    getActivity().setTitle("PROFILE");
}

答案 1 :(得分:0)

您正在尝试使用活动的功能,但是片段与它们有很大不同。 您需要在RootView中找到视图,因此需要将行更改为:

t1 = view.findViewById(R.id.username)

如果不确定如何使用片段,则还应该阅读一些有关片段的信息。 一个不错的起点可能是https://developer.android.com/guide/components/fragments

答案 2 :(得分:0)

此布局位于onViewCreated生命周期回调的视图参数中。因此,请使用view.findViewById(YOUR_ID)。 它应该工作。或者,您也可以在onActivityCreated()回调中使用getView()方法。

  

我可以知道为什么存在问题。并且在Android项目中使用Fragmnets安全吗?有更好的方法吗?

是的。当您拥有更多不断变化的用户界面并且使用片段时,生命周期回调的格式正确时,使用片段实际上是一个好习惯。了解有关

的更多信息
  

片段交易和片段

here ..

BackgroundTask希望是您的自定义类,并且不希望有片段实例。如果检查上下文,请检查Background任务的参数,并通过getActivity()

答案 3 :(得分:0)

尝试一下:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile, container, false);

    t1 = view.findViewById(R.id.username);
    //do stuff with t1 obj

    return view;
}

答案 4 :(得分:0)

在片段类中,您可以使用充气器来附加布局,如下所示。并且您可以访问以下元素:

public class BlankFragment3 extends Fragment {

public BlankFragment3() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_blank3, container, false);
     //element of xml file
    TextView mTxtTitle = (TextView) view.findViewById(R.id.txtTitle);
    mTxtTitle.setText("Helooooooo")

    return view;
}

}

答案 5 :(得分:0)

fragments中初始化视图并使用它们,您应该将片段布局膨胀并保存在View变量中,如下所示:

package com.example.dhruv.dez;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Profile extends Fragment {
    @Nullable
    private TextView t1;
    private View rootView;//View variable to save fragment layout and use it to initialize views and use them
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, 
    Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.profile, container, false);

        t1 = rootView.findViewById(R.id.username);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        getActivity().setTitle("PROFILE");


    }

}

,如果您需要将上下文传递给声明的BackgroundTask之类的类,则应通过以下方式传递上下文:

BackgroundTask b = new BackgroundTask(getActivity());

有关android中AsyncTask的更多信息,请参见this android官方文档