the argument: tools:context=".MainActivity" gives me error, addly the part named: .MainActivity appears in color red, what can i do?
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
![]()
Alec
8,4158 gold badges35 silver badges63 bronze badges
asked Apr 20, 2019 at 22:14
![]()
1
tried rebuild project or try invalidate cache restart
if still same problem you can add yourpackagename.mainactivity
like in the picture this
tools:context="com.etest.myapplicwr.MainActivity">
my packgae name is com.etest.myapplicwr
replace it with your package name
answered Aug 24, 2020 at 14:22
You can delete it, or you can update it to point to some activity or fragment where you will be using this layout resource.
answered Apr 20, 2019 at 22:16
![]()
CommonsWareCommonsWare
983k189 gold badges2383 silver badges2468 bronze badges
you should find which folder save your MainActivity.
For Example:
So, Check it.
And then, you should understand what’s its function.
it is used by: Lint, Android Studio layout editor .
This attribute declares which activity this layout is associated with by default.
This enables features in the editor or layout preview that require knowledge of the activity, such as what the layout theme should be in the preview and where to insert onClick handlers when you make those from a quickfix.
you can find more information here
answered Apr 21, 2019 at 5:25
![]()
LongaleiLongalei
4433 silver badges8 bronze badges
I encountered a problem while using Android Studio. When I’m trying to run any app, I get the same error «Default activity not found», and in my code in line tools:context=".MainActivity", MainActivity is highlighted red and it says «Unresolved class MainActivity». It happens even if I create a brand new «empty activity».
So far I’ve tried:
- refreshing IDE cache
- checked package names in Android manifest and MainActivity
- selecting a default activity in-app configuration
- made sure that src is the source directory
I’ve also noticed that in my «most advanced» app the build.gradle looks like this:

Android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.justjava">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Project directory + code:

activity main xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/coffee_grains"
android:layout_width="match_parent"
android:layout_height="300sp"
android:contentDescription="Coffee Grains"
android:scaleType="centerCrop"
android:src="@drawable/coffee_grains"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/cup"
android:layout_width="120sp"
android:layout_height="170sp"
android:layout_marginLeft="8dp"
android:src="@drawable/cup"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/coffee_grains" />
<TextView
android:id="@+id/quantity"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:layout_marginTop="16sp"
android:gravity="center"
android:text="quantity"
android:textAllCaps="true"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/coffee_grains" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/quantity">
<Button
android:id="@+id/plus"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:onClick="increment"
android:text="+" />
<TextView
android:id="@+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8sp"
android:layout_marginRight="8sp"
android:gravity="center"
android:text="1"
android:textColor="#000000"
android:textSize="14sp" />
<Button
android:id="@+id/miuns"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:onClick="decrement"
android:text="-" />
</LinearLayout>
<TextView
android:id="@+id/price"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="order summary"
android:textAllCaps="true"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/linearLayout" />
<TextView
android:id="@+id/order_summary_text_view"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="0$"
android:textSize="16dp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/price" />
<Button
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:layout_marginTop="8sp"
android:gravity="center"
android:onClick="submitOrder"
android:text="order"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/order_summary_text_view" />
</android.support.constraint.ConstraintLayout>
Main Activity file:
package com.example.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 1;
double pricePerCup = 2.90;
String name = "Pawel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void increment(View view) {
quantity = quantity +1;
displayQuantity(quantity);
}
public void decrement(View view) {
quantity = quantity - 1;
displayQuantity(quantity);
}
private String createOrderSummary(double price){
String orderSummary = "Name: " + name + "nQuantity: " + quantity +
"nTotal price: $" + price + "nThanks!";
return orderSummary;
}
private double calculatePrice(int count, double price){
return count*price;
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String message) {
TextView orderSummaryTextView =
findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
double totalPrice = calculatePrice(quantity, pricePerCup);
String priceMessage = createOrderSummary(totalPrice);
displayMessage(priceMessage);
}
/**
* This method displays the given quantity value on the screen.
*/
private void displayQuantity(int number) {
TextView quantityTextView = findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
}
Я столкнулся с проблемой при использовании Android Studio. Когда я пытаюсь запустить какое-либо приложение, я получаю ту же ошибку » tools:context=".MainActivity" умолчанию не найдено», и в моем коде в строке tools:context=".MainActivity", MainActivity выделяется красным цветом и говорит «Unresolved class MainActivity». Это происходит, даже если я создаю совершенно новую «пустую активность».
Пока что я пробовал:
- обновление кеша IDE
- проверенные имена пакетов в манифесте Android и MainActivity
- выбор активности по умолчанию в конфигурации приложения
- убедился, что src является исходным каталогом
Я также заметил, что в моем «самом продвинутом» приложении build.gradle выглядит так:

Android манифест:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.justjava">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Каталог проекта + код:

основной вид деятельности xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/coffee_grains"
android:layout_width="match_parent"
android:layout_height="300sp"
android:contentDescription="Coffee Grains"
android:scaleType="centerCrop"
android:src="@drawable/coffee_grains"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/cup"
android:layout_width="120sp"
android:layout_height="170sp"
android:layout_marginLeft="8dp"
android:src="@drawable/cup"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/coffee_grains" />
<TextView
android:id="@+id/quantity"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:layout_marginTop="16sp"
android:gravity="center"
android:text="quantity"
android:textAllCaps="true"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/coffee_grains" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/quantity">
<Button
android:id="@+id/plus"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:onClick="increment"
android:text="+" />
<TextView
android:id="@+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8sp"
android:layout_marginRight="8sp"
android:gravity="center"
android:text="1"
android:textColor="#000000"
android:textSize="14sp" />
<Button
android:id="@+id/miuns"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:onClick="decrement"
android:text="-" />
</LinearLayout>
<TextView
android:id="@+id/price"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="order summary"
android:textAllCaps="true"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/linearLayout" />
<TextView
android:id="@+id/order_summary_text_view"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="0$"
android:textSize="16dp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/price" />
<Button
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:layout_marginTop="8sp"
android:gravity="center"
android:onClick="submitOrder"
android:text="order"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/cup"
app:layout_constraintTop_toBottomOf="@id/order_summary_text_view" />
</android.support.constraint.ConstraintLayout>
Основной файл активности:
package com.example.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 1;
double pricePerCup = 2.90;
String name = "Pawel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void increment(View view) {
quantity = quantity +1;
displayQuantity(quantity);
}
public void decrement(View view) {
quantity = quantity - 1;
displayQuantity(quantity);
}
private String createOrderSummary(double price){
String orderSummary = "Name: " + name + "nQuantity: " + quantity +
"nTotal price: $" + price + "nThanks!";
return orderSummary;
}
private double calculatePrice(int count, double price){
return count*price;
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String message) {
TextView orderSummaryTextView =
findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
double totalPrice = calculatePrice(quantity, pricePerCup);
String priceMessage = createOrderSummary(totalPrice);
displayMessage(priceMessage);
}
/**
* This method displays the given quantity value on the screen.
*/
private void displayQuantity(int number) {
TextView quantityTextView = findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
}
#android
#Android
Вопрос:
аргумент: tools:context=".MainActivity" выдает ошибку, кроме того, часть с именем: .MainActivity отображается красным цветом, что я могу сделать?
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
Комментарии:
1. У вас все еще есть
MainActivity?
Ответ №1:
пробовал перестроить проект или попытаться отменить перезапуск кэша
если все та же проблема, вы можете добавить yourpackagename.mainactivity, как на картинке
tools:context="com.etest.myapplicwr.MainActivity">
мое имя пакета com.etest.myapplicwr
замените его именем вашего пакета
Ответ №2:
Вы можете удалить его или обновить, чтобы указать на какое-либо действие или фрагмент, где вы будете использовать этот ресурс макета.
Ответ №3:
вы должны найти, в какой папке вы сохраняете MainActivity . Например:
итак, проверьте это.
И затем, вы должны понять, в чем его функция.
он используется: Lint, редактором макетов Android Studio .
Этот атрибут объявляет, с каким действием этот макет связан по умолчанию.
Это позволяет использовать функции в редакторе или предварительном просмотре макета, которые требуют знания действия, например, какой должна быть тема макета в предварительном просмотре и куда вставлять обработчики onClick, когда вы создаете их из quickfix.
вы можете найти более подробную информацию здесь
#java #android #xml #android-studio
Вопрос:
В моем файле AndroidManifest отображается ошибка «Неразрешенный класс «MainActivity»», но у меня есть класс java и файл с таким именем в пакете , и он должен быть первым действием программы, поэтому, когда я пытаюсь запустить программу, она выходит из строя, я проверил свой код, но не смог найти там никаких проблем .
java-код для файла MainActivity
package com.example.tictactoe;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button forward;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forward = (Button)findViewById(R.id.start);
forward.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this,GameUi.class));
}
});
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do you want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
}
java-код для второго действия, которое использует моя программа («GameUi.java»)
package com.example.tictactoe
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class GameUi extends AppCompatActivity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_ui);
btn=(Button)findViewById(R.id.backbtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(GameUi.this, MainActivity.class));
}
});
}
}
AndroidManifest file code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tictactoe">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.TicTacToe">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GameUi">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Код xml-файла основной активности
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E5E6AD"
tools:context=".MainActivity">
<TextView
android:id="@ id/Heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_row="0"
android:layout_column="0"
android:layout_marginBottom="332dp"
android:editable="false"
android:text="Hello Aliens!"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="50dp"
android:textStyle="bold|italic"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_editor_absoluteX="16dp" />
<ImageView
android:id="@ id/Alienimg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@id/Heading"
app:srcCompat="@drawable/ic_launcher_foreground" />
<Button
android:id="@ id/Startbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000066"
android:letterSpacing="0.5"
android:padding="0dp"
android:text="Start"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/Alienimg"
app:layout_constraintVertical_bias="0.886" />
</androidx.constraintlayout.widget.ConstraintLayout>

Комментарии:
1. Вставьте свою ошибку logcat при сбое приложения.
2. пожалуйста, вставьте activity_main.xml
3. Файл (Верхнее меню) -> Аннулировать кэш / перезапустить. Это должно решить вашу проблему
Ответ №1:
В твоем классе я не вижу пакета сверху. Попробуйте добавить его и посмотрите, если вы все еще сталкиваетесь с проблемой, попробуйте аннулировать и перезапустить.
package com.example.tictactoe;
Комментарии:
1. На самом деле я добавил файлы в пакет , который я пропустил, чтобы показать это на stackoverflow, Извините, что я исправил это сейчас.
Ответ №2:
Это является причиной ошибки
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GameUi">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
фильтр намерений используется для определения того, какое действие будет вашим первым действием ( при запуске приложения для Android ). Вы можете использовать его в обоих действиях, чтобы приложение перепутало, какое из них является вашим первым действием, поэтому они выдают ошибку.
В случае, если основная активность-это ваше первое действие
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GameUi">
</activity>
Комментарии:
1. Я так не думаю. это проблема, верно. но это просто делает два приложения, которые открываются в разных видах деятельности.
2. Это не причина сбоя, я проверил это в своем приложении, работает.
3. спасибо, что указали на то, что на самом деле я тестировал свое второе действие, так что я поставил фильтр намерений, но мое приложение все еще выходит из строя, я попытался создать новый пакет, но все равно не сработало, я не думаю, что это было необходимо, но проверить, но после этого тоже не сработало
4. @Паста Ачинтяшарма activity_main.xml
Ответ №3:
Ваш манифест в порядке ( я думаю, вы исправили проблему с фильтром намерений на основе ответа Абдуллы Шейха). проблема заключается в том, что эта строка в MainActivity :
forward = (Button)findViewById(R.id.start);
потому что ваш идентификатор кнопки Startbtn не start
просто замените это на :
forward = (Button)findViewById(R.id.Startbtn);
также в activity_main и ImageView удалите
app:srcCompat="@drawable/ic_launcher_foreground"
или найдите другой src для рисования.
