Android笔记3--- Activity,碎片

[1]Activity四种状态

  1. 运行
  2. 暂停
  3. 停止
  4. 销毁

[2]Activity生命周期

Activity

[3]创建Activity:两种方式(向导和手动)

  1. 创建继承自Activity的Activity
  2. 重写需要的回调方法 --OnCreate()
  3. 设置要显示的视图 --setContentView(R.layout.activity_main) 设置布局

[4]配置Activity(向导方式不需要)

AndroidManifest.xml中设置:

<activity android:name=".DetailActivity"
				android:label="详细"></activity>

[5]启动和关闭Activity

启动

  • 关闭Activity --finish()
  • 刷新当前Activity --onCreate(null)
  • 完成跳转:
Intent yw = new Intent(MainActivity.this,ForgetPassword.class);
startActivity(yw);

[6]Bundle 以键值对的形式存在

Bundle在Activity之间交换数据

创建

//创建Intent
  Intent intent = new Intent(MainActivity.this,address.class);
//创建Bundle保存数据
  Bundle bundle = new Bundle();
  bundle.putCharSequence("name",name);
  bundle.putCharSequence("phone",phone);
  bundle.putCharSequence("site1",site1);
  bundle.putCharSequence("site2",site2);
  bundle.putCharSequence("site3",site3);
//bundle把数据交给intent
  intent.putExtras(bundle);
  startActivity(intent);

获取

 //获取intent
Intent intent =getIntent();
 //获取bundle数据
 Bundle bundle =intent.getExtras();

 String name =bundle.getString("name");
 String phone = bundle.getString("phone");
 String site = bundle.getString("site1")+bundle.getString("site2")+bundle.getString("site3");

[7]调用另一个Activity并返回结果

  • startActivityForResult(Intent intent,int requestCode) 通过请求码启动
  • 更换图像案例
//主程序中
 Intent intent = new Intent(MainActivity.this,Main2Activity.class);
                startActivityForResult(intent,0x11);
 //最后,在主程序中重写onActivityResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0x11&&resultCode==0x11){
            Bundle bundle =data.getExtras();
            int imageId = bundle.getInt("imageId");
            ImageView imageView = findViewById(R.id.add);
            imageView.setImageResource(imageId);
        }
    }               
    //资源程序中
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=getIntent();
                //新建bundle保存数据
                Bundle bundle = new Bundle();
                bundle.putInt("imageId",picture[position]);
                intent.putExtras(bundle);
                //返回码
                setResult(0x11,intent);
                finish();
            }

[8]Fragment–碎片,嵌入在活动中的UI片段

fragment

  • Fragment创建
//1.让一个类继承Fragment
//2.建立fragment布局文件
//3.重写OnCreateView方法

public class Find_Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.find_fragment,null);
        return view;
    }
}
  • 在Activity中添加Fragment
    1.直接在布局文件中添加
    2.当Activity运行时添加

通过Fragment制作简易版新闻应用
1.添加依赖库

dependencies {
   ...
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

2.新建新闻实体类

public class News {
    private String title;
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

3.新建新闻Fragment
布局news_content_frag.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"
    >

    <LinearLayout
        android:id="@+id/visibility_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="invisible">
        <TextView
            android:id="@+id/news_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:textSize="20sp"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000"/>
        <TextView
            android:id="@+id/news_content"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:padding="15dp"
            android:textSize="18sp"/>

    </LinearLayout>
    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:background="#000"/>

</RelativeLayout>

NewsContentFragment

public class NewsContentFragment extends Fragment {
    private View view;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
                    view =inflater.inflate(R.layout.fragment_news_content, container, false);
        return view;
    }
    public void refresh(String newsTitle,String newsContent){
        View visibilityLayout =view.findViewById(R.id.visibility_layout);
        visibilityLayout.setVisibility(View.VISIBLE);
        TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);
        TextView newsContentText = (TextView) view.findViewById(R.id.news_content);
        newsContentText.setText(newsContent);
        newsTitleText.setText(newsTitle);
    }

}
  1. news_content.xml
<?xml version="1.0" encoding="utf-8"?>
<!--RecyclerView的子项布局-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:ellipsize="end"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    >

</TextView>

  1. 新建新闻列表的布局 news_title_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <android.support.v7.widget.RecyclerView
        android:id="@+id/news_title_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</LinearLayout>

新闻列表的碎片中加入内部类NewsAdapter,作为RecyclerView的适配器

public class NewsTitleFragment extends Fragment {

    private boolean isTwoPane;

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

        RecyclerView newTitleRecyclerView=(RecyclerView)view.findViewById(R.id.news_title_recycler_view);
        LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());

        newTitleRecyclerView.setLayoutManager(layoutManager);
        NewsAdapter adapter=new NewsAdapter(getNews());
        newTitleRecyclerView.setAdapter(adapter);
        return view;
    }
    private List<News> getNews(){      //加入列表数据
        List<News> newsList=new ArrayList<>();
        for(int i=1;i<=50;i++){
            News news=new News();
            news.setTitle("This is news title "+i);
            news.setContent(getRandomLengthContent("This is news content "+i+"."));
            newsList.add(news);
        }
        return newsList;
    }
    private  String getRandomLengthContent(String content){  //得到随机内容的方法
        Random random=new Random();
        int length=random.nextInt(20)+1;
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<length;i++){
            builder.append(content);
        }
        return builder.toString();
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(getActivity().findViewById(R.id.news_content_layout)!=null){
            isTwoPane=true;
        }
        else {
            isTwoPane=false;
        }
    }
    class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder>{

        private List<News>mNewsList;
        class ViewHolder extends  RecyclerView.ViewHolder{

            TextView newsTitleText;
            public  ViewHolder(View view){
                super(view);
                newsTitleText=(TextView)view.findViewById(R.id.news_title);

            }
        }
        public  NewsAdapter(List<News> newsList){
            mNewsList=newsList;
        }

        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
            final ViewHolder holder = new ViewHolder(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News news = mNewsList.get(holder.getAdapterPosition());
                    if (isTwoPane) {
					//如果是双页模式,则刷新NewsContentFragment中的内容

                        NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.news_content_fragment);
                        newsContentFragment.refresh(news.getTitle(), news.getContent());
                    } else {
						//如果是单页模式,则直接启动NewsContentActivity
                        NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent());
                    }
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            News news=mNewsList.get(position);
            holder.newsTitleText.setText(news.getTitle());
        }

        @Override
        public int getItemCount() {
            return mNewsList.size();
        }
    }

}

  1. RecyclerView子项布局 news_item.xml
<?xml version="1.0" encoding="utf-8"?>
<!--RecyclerView的子项布局-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:ellipsize="end"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    >

</TextView>

  1. 修改主布局代码:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/news_title_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<!--单页模式下,只会加载一个新闻标题的碎片-->
    <fragment
        android:id="@+id/news_title_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="appstore.xianchuang.com.fragmentbestpractice.NewsTitleFragment"/>

</FrameLayout>
  1. 新建一个layout_sw600dp文件夹,建 activity_main.xml,必须通过复制的方法建 立,要不然不成功
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:id="@+id/news_title_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <fragment
        android:id="@+id/news_title_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="appstore.xianchuang.com.fragmentbestpractice.NewsTitleFragment"/>
    <FrameLayout
        android:id="@+id/news_content_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        >
        <fragment
            android:id="@+id/news_content_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="appstore.xianchuang.com.fragmentbestpractice.NewsContentFragment"/>

    </FrameLayout>

</LinearLayout>

1. Android 的基本概念 Android 是一个开源的操作系统,主要用于移动设备,如智能手机、平板电脑等。它基于 Linux 内核,提供了丰富的应用程序框架和 API,支持多种开发语言,如 Java、C/C++、Kotlin 等。 Android 应用程序由多个组件组成,包括活动(Activity)、服务(Service)、广播接收器(Broadcast Receiver)和内容提供器(Content Provider)等。这些组件可以组合在一起,形成复杂的应用程序。 2. Android 应用程序开发 Android 应用程序开发主要使用 Java 编程语言和 Android SDK。开发工具包括 Android Studio、Eclipse 等。 Android 应用程序的结构包括布局文件、资源文件、Java 代码和清单文件等。布局文件用于定义应用程序的用户界面,资源文件包括图像、声音、样式、主题等,Java 代码实现应用程序的逻辑,清单文件描述应用程序的组件和权限等信息。 3. Android 应用程序的调试和测试 Android 应用程序的调试和测试可以使用 Android Studio 提供的调试工具,包括断点调试、日志记录等。还可以使用模拟器或真实设备进行测试。 4. Android 应用程序的发布 发布 Android 应用程序需要进行签名和打包操作,签名用于验证应用程序的身份和完整性,打包将应用程序打包成 APK 文件,可以上传到应用商店进行发布。 5. Android 应用程序的优化 Android 应用程序的优化包括优化布局、资源、代码和网络等方面,以提高应用程序的性能和用户体验。其中,布局优化包括使用布局最优化算法、使用自定义视图等;资源优化包括压缩资源、使用向量图形等;代码优化包括使用异步任务、使用缓存等;网络优化包括使用数据压缩、使用本地存储等。 6. Android 开发的挑战 Android 开发面临的挑战包括设备碎片化、安全问题、性能问题等。设备碎片化指的是不同设备的屏幕尺寸、分辨率、操作系统版本等不同,需要对应用程序进行适配;安全问题指的是应用程序需要保证用户数据的安全和隐私;性能问题指的是应用程序需要保证快速响应和流畅运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值