在片段中findViewById而不放入onCreateView

时间:2018-03-26 19:33:02

标签: android fragment

我想知道可以在onCreateView方法之外设置我的TextView。

以下是在Android studio上成功运行的代码

public class TabMatchFragmentOdd extends Fragment {
    TextView Home, Away;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_match_odd, container, false);
        Home = (TextView) v.findViewById(R.id.homename);
        Away = (TextView) v.findViewById(R.id.awayname);
        getIncomingIntent();

        return v;
    }

    private void getIncomingIntent() {
        if (getActivity().getIntent().hasExtra("HomeName") && getActivity().getIntent().hasExtra("AwayName")) {
            String HomeName = getActivity().getIntent().getStringExtra("HomeName").toString();
            String AwayName = getActivity().getIntent().getStringExtra("AwayName").toString();
            setContent(HomeName,AwayName);        
        } else {
            Toast.makeText(getActivity(), "No", Toast.LENGTH_SHORT).show();
        }
    }

    private void setContent(String home, String away) { 
        Home.setText(home);
        Away.setText(away);
    }
}

但我希望通过特定的方法使代码更清晰

我能以类似的方式做到吗?

public class TabMatchFragmentOdd extends Fragment {
    TextView Home, Away;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v;
         v = inflater.inflate(R.layout.tab_match_odd, container, false);
        getIncomingIntent();
        return v;

    }

    private void getIncomingIntent() {
        if(getActivity().getIntent().hasExtra("HomeName")&&getActivity().getIntent().hasExtra("AwayName")) {
            String HomeName = getActivity().getIntent().getStringExtra("HomeName").toString();
            String AwayName = getActivity().getIntent().getStringExtra("AwayName").toString();
            setContent(HomeName,AwayName);         
        }else{
            Toast.makeText(getActivity(), "No:", Toast.LENGTH_SHORT).show();
        }
    }

    private void setContent(String home, String away) {
        Home = (TextView) getActivity().findViewById(R.id.homename);
        Away = (TextView) getActivity().findViewById(R.id.awayname);      
        Home.setText(home);
        Away.setText(away);
    }
}

运行应用程序后,它会给我一个NullPointException

无论我使用getActivity()还是getView(),都无效。

背后的概念是什么?

3 个答案:

答案 0 :(得分:3)

bin\cake migrations help migrate 的{​​{1}}与您Layout的{​​{1}}无关,因此Fragment会失败。

Layout充气后Activity执行以下操作:

getActivity().findViewById

一些编码风格提示:让onCreateView访问Layout。在命名时,请从Home = (TextView) v.findViewById(R.id.homename); 开始,并将TextView添加到最后,以便您知道privatelowercase

答案 1 :(得分:2)

  

运行应用程序后,它出现nullpointexception错误

     

无论我使用getActivity()还是getView(),它都无法正常工作。

     

背后的概念是什么?

当您致电getView()时,您将获得以下结果:

  • 如果onCreateView()尚未完成,则getView()会返回null
  • 如果onCreateView()已完成,getView()将返回您在onCreateView()
  • 中返回的内容

在您的代码中,setContent()会调用getIncomingIntent()onCreateView()会调用onCreateView()。这意味着getView()尚未完成,因此getIncomingIntent()此时将始终返回null。

您可以对第二段代码进行的最小更改是将onCreateView()来电从onViewCreated()转移到public class TabMatchFragmentOdd extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.tab_match_odd, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getIncomingIntent(); } private void getIncomingIntent() { if (getActivity().getIntent().hasExtra("HomeName") && getActivity().getIntent().hasExtra("AwayName")) { String HomeName = getActivity().getIntent().getStringExtra("HomeName").toString(); String AwayName = getActivity().getIntent().getStringExtra("AwayName").toString(); setContent(HomeName, AwayName); } else { Toast.makeText(getActivity(), "No:", Toast.LENGTH_SHORT).show(); } } private void setContent(String home, String away) { TextView Home = getView().findViewById(R.id.homename); TextView Away = getView().findViewById(R.id.awayname); Home.setText(home); Away.setText(away); } }

import { Component } from '@angular/core';
import {Post} from "./post"
import {PostService} from "./post.service";
import {Observable} from "rxjs/Observable";
import {Img} from "./img";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [PostService]
})
export class AppComponent {
  title = 'app';
  myWrapperList: Array<MyWrapper> = []; 

  constructor(private postService: PostService) { }
  ngOnInit(): void {
    this.init();
  }

  init(): void {

    this.postService.getPosts().subscribe( posts => 

       posts.forEach(post => {
           this.postService.getImgsByPostId(post.postId).subscribe(imgs => 
             let myWrapper = new MyWrapper(post, imgs);
             this.myWrapperList.push(myWrapper);
       });

    );
  }

}


export class MyWrapper {
    constructor(
      public post: Post,
      public images: Array<Images>
    ){}
}

答案 2 :(得分:1)

首先关于夸大观看次数:

这段代码:

java.io.FileNotFoundException: Code,Description,Code Type,Format Group,Format Subgroup,Category Group,Category Subgroup (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at java.io.FileInputStream.<init>(FileInputStream.java:79)
    at java.io.FileReader.<init>(FileReader.java:41)
    at StubMapper.getMapFromCSV(StubMapper.java:27)
    at StubMapper.map(StubMapper.java:50)
    at StubMapper.map(StubMapper.java:14)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:140)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:673)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:331)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:268)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:396)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1408)
    at org.apache.hadoop.mapred.Child.main(Child.java:262)

&#34;充气&#34;视图意味着它需要xml文件并只创建所有这些对象。所以在那之后v是一个包含xml中定义的所有其他视图的视图。这就是你可以使用的原因:

View v;
v = inflater.inflate(R.layout.tab_match_odd, container, false);

因为此TextView是View中的definec。

getView()和getActivity()差异

另一件事是你的片段被托管了#34;按活动。它也有它的视图(通过使用setContentView(...)方法膨胀)。通过这个你可以使用Activity.findViewById(),你将能够找到在Activity的xml文件中膨胀的视图(在setContentView()中设置)。 这就是原因:

(TextView) v.findViewById(R.id.awayname);

有效,

(TextView) v.findViewById(R.id.awayname);

没有按&#39;吨。活动根本没有夸大包含R.id.awayname的视图。 如你所见:getActivity()只返回&#34; hosting&#34;片段和getView()返回您从onCreateView()方法返回的视图。

为什么getView()产生null?

这是因为你在onCreateView()返回语句之前使用了getView()方法。

怎么做?

为了使其工作,在你的片段/活动中创建属性是明智的:

public class TabMatchFragmentOdd extends Fragment { TextView Home,Away;

(TextView) getActivity().findViewById(R.id.awayname);